asyncio での開発
from asyncioについてのメモ
asyncio での開発
Pythonドキュメントにあるasyncioを使った開発のヒント
https://docs.python.org/ja/3.13/library/asyncio-dev.html#developing-with-asyncio
asyncioのデバッグモードを使用すると良い
code:py
asyncio.run(debug=True)
コルーチン
async defで宣言できる非同期関数
asyncioでは、async.create_task()を用いてコルーチンをスケジュールする
スケジュール=登録するみたいな概念?
コルーチンはawaitで必ず待ち受けられなければいけない
TaskGroup()では暗黙的に呼び出される
code:py
async def sleep_after(delay, who):
logger.info("%s: hi! ...", who)
await asyncio.sleep(delay)
logger.info("%s: good bye!", who)
async def gather_demo_():
async with asyncio.TaskGroup() as tasks:
tasks.create_task(sleep_after(1.0, "pierre"))
tasks.create_task(sleep_after(3.0, "john"))
logger.info("are they executed concurrently?")
async def main():
await gather_demo_alt()
asyncio.run(main(), debug=True)
Pythonのイベントループ
Pythonのイベントループはメインスレッド内で動作する
全てのコールバックとタスクはそのスレッドの中で実行される
一つのタスクがイベントループの中で実行されている間は、他のタスクを同じスレッド内で実行することはできない(排他的)
awaitを実行すると、実行中のタスクはサスペンドされイベントループは次のタスクを実行する
サスペンドってなんだ
multiprocessingでは、別のプロセスからコルーチンやコールバックをスケジュールすることが可能だが、asyncioでは不可
loop.run_in_executor()メソッドは、concurrent.futures.ProcessPoolExecutor とともに使用することで、別のプロセス内でコードを実行可能
同期処理的なコードを非同期処理のコンテキストの中で動かせて便利